package logic

import (
	"context"
	"errors"
	"manuscript-service/manrpc/internal/svc"
	"manuscript-service/manrpc/manrpc"
	"manuscript-service/model/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManAddLogic {
	return &ManAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ManAddLogic) ManAdd(in *manrpc.ManAddRequest) (*manrpc.ManAddResponse, error) {
	// todo: add your logic here and delete this line

	begin := mysql.DB.Begin()

	var manuscripts mysql.Manuscript
	err := manuscripts.FindTitle(begin, in.Title)
	if err != nil {
		begin.Rollback()
		return nil, errors.New("当前标题已存在，请更换")
	}

	m := &mysql.Class{
		Name: in.ClassName,
	}
	if err := m.ClassNameAdd(begin, in.ClassName); err != nil {
		begin.Rollback()
		return nil, err
	}

	manuscript := &mysql.Manuscript{
		Title:   in.Title,
		Info:    in.Info,
		ClassId: int(m.ID),
	}

	if err := manuscript.ManAdd(begin); err != nil {
		begin.Rollback()
		return nil, err
	}

	begin.Commit()

	return &manrpc.ManAddResponse{
		ManId: int64(manuscript.ID),
	}, nil
}
